#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2018/10/25

import re
import json
import requests
############获取目的地出差时间范围内，是否有预警信息#############

############实时爬取分析#################


########警告等級
def degree(kind,grade):
    gradeObj = {
        "01": "蓝色",
        "02": "黄色",
        "03": "橙色",
        "04": "红色",
        "05": "白色"
    }
    kindObj = {
        "01": "台风",
        "02": "暴雨",
        "03": "暴雪",
        "04": "寒潮",
        "05": "大风",
        "06": "沙尘暴",
        "07": "高温",
        "08": "干旱",
        "09": "雷电",
        '10': "冰雹",
        '11': "霜冻",
        '12': "大雾",
        '13': "霾",
        '14': "道路结冰",
        '91': "寒冷",
        '92': "灰霾",
        '93': "雷雨大风",
        '94': "森林火险",
        '95': "降温",
        '96': "道路冰雪",
        '97': "干热风",
        '98': "空气重污染",
        '99': "低温",
        '51': "海上大雾",
        '52': "雷暴大风",
        '53': "持续低温",
        '54': "浓浮尘",
        '55': "龙卷风",
        '56': "低温冻害",
        '57': "海上大风",
        '58': "低温雨雪冰冻",
        '59': "强对流",
        '60': "臭氧",
        '61': "大雪",
        '62': "强降雨",
        '63': "强降温",
        '64': "雪灾",
        '65': "森林（草原）火险",
        '66': "雷暴",
        '67': "严寒",
        '68': "沙尘",
        '69': "海上雷雨大风",
        '70': "海上雷电",
        '71': "海上台风",
        '72': "低温"
    }

    return kindObj[kind]+gradeObj[grade]

################爬蟲框架###############################
def spider_warning():
    #获取所有的预警数据； 字典 城市cod  ：【时间，警告等级，城市中文】
    url = 'http://product.weather.com.cn/alarm/grepalarm_cn.php?_=1540438887460'
    res=  requests.get(url).text.encode('latin1').decode('utf-8')
    # 转化为字典格式
    reg = re.sub(r'var alarminfo=', '', res)[:-1]

    context_list = json.loads(reg)['data']
    context_list_all = {}
    for x in context_list:
        code = x[1].replace('.html','').split('-')
        code.append(x[0])

        if code[0] not in context_list_all.keys():
            context_list_all[code[0]] = code[1:]
        else:
            context_list_all[code[0]].append(code[1:])

    return context_list_all


def main_warning(code_ch,code,time_cf,time_fh):
    #通过是否存在某个省份，所有都展示出来
    spider_warn_dic = spider_warning()
    code_th = spider_warn_dic.get(code)
    warning_text = ''
    if code_th:
        for x in  code_th:
            if time_cf <= x[0][:8] <=  time_cf:
                degre = degree(str(code_th[1][:2]),str(code_th[1][2:]))
                warning_text += x[0][:8]
                warning_text+= code_ch
                warning_text += degre
                warning_text += '预警'

    print(warning_text)
    return warning_text


if __name__ == '__main__':

    main_warning('云南','101090217','20181025  ','20181030')#


